<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\Product;

use App\Models\Footprint;
use App\Models\Product;
use App\Models\User;
use App\Service\BaseService;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class ProductService extends BaseService
{
    /**
     * 足迹.
     * @param Product $product
     * @param mixed $product_id
     * @return Builder|Builder[]|Collection|Model|void
     */
    public function footprint(User $user, $product_id)
    {
        Footprint::track($user, $product_id);
    }

    /**
     * 查询商品
     * @return Builder[]|Collection
     */
    public function search(string $search)
    {
        return Product::query()
            ->select(['name', 'id', 'subtitle', 'main_image', 'sold_num', 'price'])
            ->where('status', '<>', 0)
            ->where('name', 'like', '%' . $search . '%')
            ->get();
    }

    /**
     * 基础列表.
     *
     * @param null $category_id
     * @param null $type
     * @return Paginator|void
     */
    public function baseList($category_id = null, $type = null)
    {
        $perPage = request()->get('perPage', 20);
        return Product::query()
            ->select(['name', 'id', 'subtitle', 'main_image', 'sold_num', 'price', 'stock'])
            ->where('status', '<>', 0)
            ->when($type, function ($query, $type) {
                switch ($type) {
                  case 'is_hot':
                      $query->where('is_hot', 1);
                      break;
                  case 'is_new':
                      $query->where('is_new', 1);
                      break;
                  case 'is_recommend':
                      $query->where('is_recommend', 1);
                      break;
                  case 'is_farmers':
                      $query->where('is_farmers', 1);
                      break;
                  case 'is_specialty':
                      $query->where('is_specialty', 1);
                      break;
              }
            })
            ->when($category_id, function ($query, $category_id) {
                $query->where('category_id', $category_id);
            })
            ->orderByDesc('sort')
            ->simplePaginate($perPage);
    }
}
